'''
Created on 16 Apr 2012

@author: karulis
'''

from PySide import QtGui
from BaseTab import BaseTab

class EditTab(BaseTab):
    '''
    classdocs
    '''


    def __init__(self, parent = None):
        '''
        Constructor
        '''
        super(EditTab, self).__init__(parent)

        userLabel = QtGui.QLabel("User:")
        self.combo = QtGui.QComboBox()
        self.combo.currentIndexChanged[str].connect(self.update_fields)
        disableLabel = QtGui.QLabel("Disable account:")
        self.disableButton = QtGui.QCheckBox()
        homeLabel = QtGui.QLabel("Home directory:")
        self.homeEdit = QtGui.QLineEdit()
        shellLabel = QtGui.QLabel("Shell:")
        self.shellEdit = QtGui.QLineEdit()

        buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Save
                                           | QtGui.QDialogButtonBox.Cancel)
        buttonBox.setCenterButtons (True)
        buttonBox.accepted.connect(self.update)
        buttonBox.rejected.connect(self.reload_fields)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(userLabel)
        mainLayout.addWidget(self.combo)
        mainLayout.addWidget(disableLabel)
        mainLayout.addWidget(self.disableButton)
        mainLayout.addWidget(homeLabel)
        mainLayout.addWidget(self.homeEdit)
        mainLayout.addWidget(shellLabel)
        mainLayout.addWidget(self.shellEdit)
        mainLayout.addWidget(buttonBox)
        mainLayout.addStretch(1)
        self.setLayout(mainLayout)
        self.refresh_gui()

    def update(self):
        if self.disableButton.isChecked():
            lockOption = " --lock "
        else:
            lockOption = " --unlock "

        ret = self.execute("usermod --home " + self.homeEdit.text()
                + " --shell " + self.shellEdit.text()
                + lockOption + self.combo.currentText())
        if "" != ret:
            self.show_message(ret)
        else:
            self.show_message("Data saved")

    def reload_fields(self):
        self.update_fields(self.combo.currentText())

    def refresh_gui(self):
        self.combo.clear()
        users = self.get_users()
        self.combo.addItems(users.keys())
        user = self.combo.currentText()
        self.update_fields(user)

    def update_fields(self, user):
        if user != "":
            users = self.get_users()
            self.homeEdit.setText(users[user][0])
            self.shellEdit.setText(users[user][1])
            userStatus = self.execute("passwd -S " + user)
            if userStatus.split()[1] == "L":
                self.disableButton.setChecked(True)
            else:
                self.disableButton.setChecked(False)
